package com.rongxue.controller.payment;

import com.rongxue.mapper.SProjectMapper;
import com.rongxue.mapper.SUserDueDetailMapper;
import com.rongxue.mapper.SUserMapper;
import com.rongxue.pojo.ObjectResult;
import com.rongxue.pojo.SProject;
import com.rongxue.pojo.SUserDueDetail;
import com.rongxue.pojo.XMLBean;
import com.rongxue.service.ProjectService;
import com.rongxue.service.utils.MobileUtil;
import com.rongxue.utils.CommonUtils;
import com.rongxue.utils.DateUtil;
import com.rongxue.utils.Page;
import org.apache.commons.lang3.StringEscapeUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.util.*;

import static java.math.BigDecimal.ROUND_HALF_DOWN;


@Controller
public class ProjectController {

    @Autowired
    private ProjectService projectService;

    @Autowired
    private HttpServletRequest request;
    @Autowired
    HttpServletResponse response;

    @Autowired
    private SProjectMapper sProjectMapper;
    @Autowired
    private SUserMapper sUserMapper;
    @Autowired
    private SUserDueDetailMapper sUserDueDetailMapper;

    private static final Logger logger = LoggerFactory.getLogger(ProjectController.class);

    //用户投资
    @ResponseBody
    @RequestMapping(value = "/tender/tender", method = RequestMethod.POST, produces = "application/json")
    public ObjectResult tender(XMLBean xmlBean){

        logger.info("參數：" + xmlBean);
        //传输参数
        if (xmlBean.getToken() == null || xmlBean.getToken().equals("") || xmlBean.getAmoney() == null || xmlBean.getAmoney().equals("") || xmlBean.getDevice_type() == null
                || xmlBean.getDevice_type().toString().equals("") || xmlBean.getProject_id() == null || xmlBean.getProject_id().equals("") || xmlBean.getMoney() == null
                || xmlBean.getMoney().equals("") || xmlBean.getPay_type() == null || xmlBean.getPay_type().equals("")){

            return ObjectResult.build("0", "参数丢失,请重试");
        }
        BigDecimal amoney = new BigDecimal(xmlBean.getAmoney());
        BigDecimal[] results = amoney.divideAndRemainder(BigDecimal.valueOf(100));
        if (results[1] != BigDecimal.valueOf(0)){
            return ObjectResult.build("0", "投资金额必须是100的整数");
        }
        ObjectResult result = projectService.tender(xmlBean);
        return result;
    }


    //投资回调报文验证
    @ResponseBody
    @RequestMapping(value = "tender/tenderNotify", method = RequestMethod.POST, produces = "application/json")
    public ObjectResult tenderNotify(String TYPE, String VERSION, String RESPONSECODE, String RESPONSEMSG, String MCHNTCD, String MCHNTORDERID,
                                     String ORDERID, String AMT, String BANKCARD, String SIGN){

        logger.info("投资回调报文=========="+"TYPE---"+TYPE+"VERSION---"+VERSION+"RESPONSECODE---"+RESPONSECODE+"RESPONSEMSG---"+RESPONSEMSG+"MCHNTCD---"+MCHNTCD
                +"MCHNTORDERID---"+MCHNTORDERID+"ORDERID---"+ORDERID+"AMT---"+AMT+"BANKCARD---"+BANKCARD+"SIGN---"+SIGN);
        ObjectResult ObjectResult = projectService.verificationTenderNotify(TYPE, VERSION, RESPONSECODE, RESPONSEMSG, MCHNTCD, MCHNTORDERID, ORDERID, AMT, BANKCARD, SIGN);

        return ObjectResult;
    }

//    /**
//     * 产品列表
//     * @param xmlBean
//     * @return
//     */
    @RequestMapping(value = "/project/project_list")
    @ResponseBody
    public ObjectResult project_list(XMLBean xmlBean) {
        Map<String,Object> data = new HashMap<String,Object>();
        try {
            List<SProject> list = sProjectMapper.selectProjectListByStatus();
//            Page<SProject> page = new Page<>();
//            page.setP(xmlBean.getP());
//            page.setPageSize(10);
//            List<SProject> content = page.getPageContent(list);
            List<SProject> list2 = new ArrayList<>();
            List<SProject> list3 = new ArrayList<>();
            List<SProject> list5 = new ArrayList<>();
            Integer count = 0;
            for (SProject sProject:list){
                if (sProject.getStatus()==2){
                    list2.add(sProject);
                }
                if (sProject.getStatus()==3 || sProject.getStatus()==6 || sProject.getStatus()==5){
                    if (count<=1) {
                        list3.add(sProject);
                        count++;
                    }
                }
//                if (sProject.getStatus()==5){
//                    list5.add(sProject);
//                }
            }
            data.put("list2",list2);
            data.put("list3",list3);
//            data.put("list5",list5);
//            data.put("count",page.getPageTotal());
            return  ObjectResult.build("1","成功",data);
        }catch (Exception e){
            e.printStackTrace();
            return  ObjectResult.build("0","失败");
        }

    }


    /**
     * 产品列表
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/project/project_list2")
    @ResponseBody
    public ObjectResult project_list2(XMLBean xmlBean) {
        Map<String,Object> data = new HashMap<String,Object>();
        try {
            List<SProject> list = sProjectMapper.selectProjectListByStatus();
//            Page<SProject> page = new Page<>();
//            page.setP(xmlBean.getP());
//            page.setPageSize(10);
//            List<SProject> content = page.getPageContent(list);
            List<SProject> list2 = new ArrayList<>();
            List<SProject> list3 = new ArrayList<>();
            List<SProject> list5 = new ArrayList<>();

            Integer count = 0;
            for (SProject sProject:list){
//                sProject.setDuration(DateUtil.getDaysBetweenToDate(sProject.getEndTime(),new Date()));
                if (sProject.getStatus()==2){
                    list2.add(sProject);
                }
                if (sProject.getStatus()==3 || sProject.getStatus()==6){
                    if (count<=1) {
                        list3.add(sProject);
                        count++;
                    }
                }
            }

            Map<String,Object> map1 = new HashMap<>();
            Map<String,Object> map2 = new HashMap<>();
            Map<String,Object> map3 = new HashMap<>();
            map1.put("list",list2);
            map2.put("list",list3);
            Object[] array = {map1,map2};
            return  ObjectResult.build("1","成功",array);
        }catch (Exception e){
            e.printStackTrace();
            return  ObjectResult.build("0","失败");
        }
    }


    /**
     * 产品列表
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/project/project_list3")
    @ResponseBody
    public ObjectResult project_list3(XMLBean xmlBean) {
        Map<String,Object> data = new HashMap<String,Object>();
        try {
            List<SProject> list = sProjectMapper.selectProjectListByStatus2(xmlBean.getStatus());
            if(xmlBean.getStatus()==3){
                List<SProject> list1 = sProjectMapper.selectProjectListByStatus2(6);
                for (SProject sProject:list1){
                    list.add(sProject);
                }

            }
            Page<SProject> page = new Page<>();
            page.setP(xmlBean.getP());
            page.setPageSize(10);
            List<SProject> content = page.getPageContent(list);
            for (SProject sProject:content){
                sProject.setIdcard(sProject.getIdcard().substring(0,1)+"*****************");
                sProject.setRealName(sProject.getRealName().substring(0,1)+"**");
            }
            data.put("list",content);
            data.put("count",page.getPageTotal());
            return  ObjectResult.build("1","成功",data);
        }catch (Exception e){
            e.printStackTrace();
            return  ObjectResult.build("0","失败");
        }
    }



    public static String getTextFromTHML(String htmlStr) {
        Document doc = Jsoup.parse(htmlStr);
        String text = doc.text();
        // remove extra white space
        StringBuilder builder = new StringBuilder(text);
        int index = 0;
        while(builder.length()>index){
            char tmp = builder.charAt(index);
            if(Character.isSpaceChar(tmp) || Character.isWhitespace(tmp)){
                builder.setCharAt(index, ' ');
            }
            index++;
        }
        text = builder.toString().replaceAll(" +", " ").trim();
        return text;
    }
    /**
     * 产品详情
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/project/project_detail")
    @ResponseBody
    public ObjectResult project_detail(XMLBean xmlBean) {
        Map<String,Object> map = new HashMap<>();

        SProject data = projectService.selectProjectByPid(xmlBean.getId());
        data.setInterest_accrual_time(DateUtil.formatDate(DateUtil.addDateDay(DateUtil.parseDate(data.getStart_time()),1)));
        BigDecimal decimal = data.getAmount().multiply(data.getUser_interest().divide(new BigDecimal(100))).multiply(new BigDecimal(data.getDuration())).divide(new BigDecimal(365),2,ROUND_HALF_DOWN);
//        data.setDuration(DateUtil.getDaysBetweenToDate(data.getEndTime(),new Date()));
        data.setTotal_revenue(decimal);
        data.setPeriods(data.getTitle().substring(data.getTitle().lastIndexOf("】")+1));//截取期数

        SUserDueDetail sUserDueDetail = sUserDueDetailMapper.selectInvestmentMax(xmlBean.getId());
        data.setSource("即每月偿还出借人同等数额的还款金额(包括本金和利息),具体来说，借款人每月偿还的本金比重逐月递增，利息比重逐月递减。");
        if(sUserDueDetail==null){
            data.setTycoon("抢先成为本项目投资额最高的土豪,将有机会获得"+data.getTycoon_value()+"元土豪红包！");
        }else {
            data.setTycoon("恭喜"+ CommonUtils.concealMobile(sUserDueDetail.getMobile())+"用户抢先成为本项目投资额最高的土豪，累计投资高达"+sUserDueDetail.getDue_capital()+"元;他将有机会获得"+data.getTycoon_value()+"元土豪红包，超过他，红包就是您的！");//土豪奖
        }
        data.setLast("最后一位投资的用户将获得"+data.getLast_valiu()+"元收官红包，本项目剩余可投金额"+data.getAble()+"元，蓄势待发，红包等你拿！");//收官奖
        data.setInvest_direction(getTextFromTHML(StringEscapeUtils.unescapeHtml4(data.getInvest_direction())));


        return  ObjectResult.build("1","成功",data);
    }

    @RequestMapping(value = "/project/project_details")
    @ResponseBody
    public ObjectResult project_details(XMLBean xmlBean) throws IOException {
        SProject sProject = sProjectMapper.selectProjectDetailByPid(xmlBean.getId());

        List<Map<String,Object>> list = new ArrayList<>();

        String[] split = sProject.getImage().split("src");
        for (int i =0;i<split.length-1;i++){
            Map<String,Object> map = new HashMap<>();
            if(split[i+1].contains("http")&split[i+1].contains("jpg")){
                map.put("src",split[i+1].substring(split[i+1].lastIndexOf("http"), split[i+1].lastIndexOf(".jpg") + 4));
            }
            else if(split[i+1].contains("http")&split[i+1].contains("png")){
                map.put("src",split[i+1].substring(split[i+1].lastIndexOf("http"), split[i+1].lastIndexOf(".png") + 4));
            }else {
                map.put("src","");
            }

//            if(!map.get("src").equals("")) {
//                //获取图片高度
//                URL url = new URL(map.get("src").toString());
//                URLConnection urlConnection = url.openConnection();
//                int length = urlConnection.getContentLength();
//                if (length == -1) {
//                    map.put("img_heigh","0");
//                } else {
//                    BufferedImage sourceImg = ImageIO.read(url);
//                    map.put("img_heigh",sourceImg.getHeight() + "");
//                }
//            }
//            else {
//                map.put("img_heigh","0");
//            }
            list.add(map);
        }
        sProject.setImgList(list);

        return  ObjectResult.build("1","成功",sProject);
    }
    /**
     * 项目资料详情
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/project/particulars")
    public ModelAndView particulars(XMLBean xmlBean) {
        SProject project = sProjectMapper.selectProjectAllById(xmlBean.getId());
        String projectDetail = project.getProjectDetail();
        ModelAndView modelAndView = new ModelAndView("msg");
        modelAndView.addObject("msg", StringEscapeUtils.unescapeHtml4(projectDetail));
        return modelAndView;
    }

    /**
     * 资金保障页面
     * @param xmlBean
     */
    @RequestMapping(value = "/project/fund_guarantee")
    public ModelAndView fund_guarantee(XMLBean xmlBean) {
        SProject project = sProjectMapper.selectProjectAllById(xmlBean.getId());
        String investPriceBao = project.getInvestPriceBao();
        ModelAndView modelAndView = new ModelAndView("msg");
        modelAndView.addObject("msg", StringEscapeUtils.unescapeHtml4(investPriceBao));
        return modelAndView;
    }

    /**
     * 产品投资列表
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/project/invest_list")
    @ResponseBody
    public ObjectResult invest_list(XMLBean xmlBean) {
        Map<String,Object> map = new HashMap<String,Object>();
        Map<String,Object> data = new HashMap<String,Object>();
        BigDecimal total_money = new BigDecimal(0);
        List<SProject> list = projectService.selectProjectInvestList(xmlBean.getId());
        Page<SProject> page = new Page<>();
        page.setP(xmlBean.getP());
        page.setPageSize(10);
        List<SProject> content = page.getPageContent(list);
        for (SProject sProject :list){
            total_money = sProject.getAmount().add(total_money);
            sProject.setAdd_time(sProject.getAdd_time().substring(0,sProject.getAdd_time().lastIndexOf(".")));
        }

        data.put("list",content);
        data.put("headcount",page.getRecordTotal());
        data.put("count",page.getPageTotal());
        data.put("total_money",total_money);

        return  ObjectResult.build("1","成功",data);
    }

    /**
     * 排行榜
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/project/rank")
    @ResponseBody
    public ObjectResult rank(XMLBean xmlBean) {
        return projectService.rank(xmlBean);
    }

    /**
     * 借款合同
     * @param xmlBean
     * @return
     */
    @RequestMapping("/project/contract")
    @ResponseBody
    public ObjectResult contract(XMLBean xmlBean)  {
        if(xmlBean.getToken()==null||xmlBean.getToken().equals(""))  return ObjectResult.build("0","未登录");
        return projectService.loanContract(xmlBean);

    }

}
